﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
#if WINDOWS_PHONE
using Microsoft.Xna.Framework.Input.Touch;
#endif
namespace Brain
{
    public class VirtualThumbstick
    {
        public Vector2 Position;
        protected Vector2 CurrentPosition;

        public Rectangle ThumbstickRectangle;

        public int MaxDistance = 128;

        public VirtualThumbstick(Vector2 position, int size)
        {
            this.Position = position;
            CurrentPosition = position;
            ThumbstickRectangle = new Rectangle((int)position.X, (int)position.Y, size, size);
        }

        public bool Using;

        public Vector2 Difference;

        public virtual void Update()
        {
            ThumbstickRectangle = new Rectangle((int)CurrentPosition.X, (int)CurrentPosition.Y, ThumbstickRectangle.Width, ThumbstickRectangle.Height);
#if WINDOWS_PHONE
            bool foundOne = false;
            for (int i = 0; i < Engine.Instance.InputManager.Touches.Count; i++)
            {
                TouchLocation touch = Engine.Instance.InputManager.Touches[i];
                Vector2 touchPos = touch.Position;
                Rectangle rect = new Rectangle((int)touchPos.X, (int)touchPos.Y, 1, 1);
                if (rect.Intersects(ThumbstickRectangle))
                {
                    foundOne = true;
                    Using = true;
                    CurrentPosition = touchPos - new Vector2(ThumbstickRectangle.Width / 2);
                    CurrentPosition = Vector2Util.Clamp(CurrentPosition, Position.X - MaxDistance,
                        Position.X + MaxDistance, Position.Y - MaxDistance,
                        Position.Y + MaxDistance);
                    break;
                }
            }
            Difference = CurrentPosition - Position;
            float X = Difference.X / this.MaxDistance;
            float Y = Difference.Y / this.MaxDistance;
            Difference = new Vector2(X, Y);
            if (Using && !foundOne)
            {
                Using = false;
                CurrentPosition = Position;
            }
#endif
        }
    }
}
